﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Jamhee.Noctiluca.LightWiki.Markup
{
    class Link : WikiMarkup
    {
        // Sample: {link:url=http://www.google.com|title=google|window=new}
        private const string LINK = @"\{link:(url=([^\|]+))(\|title=([^\|]+))?(\|window=([^\|]+))?}";

        protected override string ConvertMarkup(string text, string docFolder, Uri url, MarkupStack stack, Regex regex)
        {
            string html = text;
            MatchCollection matches = regex.Matches(html);
            foreach (Match match in matches)
            {
                if (match.Groups.Count == 7)
                {
                    string linkUrl = match.Groups[2].Value;
                    string diplayText = match.Groups[4].Value;
                    string newWindow = match.Groups[6].Value;

                    if (diplayText.Length == 0)
                    {
                        diplayText = linkUrl;
                    }

                    string linkTarget = "";
                    if (newWindow.ToLower().Equals("new"))
                    {
                        // Open the link in a new window
                        linkTarget = "target=\"_blank\"";
                    }

                    html = regex.Replace(html, "<a href =\"" + CovertURL(linkUrl, url, false) + "\" " + linkTarget + ">" + diplayText + "</a>");
                }
            }

            return html;
        }

        protected override string MarkupRegEx
        {
            get { return LINK; }
        }

        public override bool AddParagraphMarkup
        {
            get { return true; }
        }
    }
}
